<template>
    <el-form ref="form-components" :model="form" :inline="inline" :label-width="labelWidth" :rules="rules">
        <slot></slot>
        <el-form-item class="reason-btn" v-if="formTypeInfo.formType == 'submit'">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submit" :loading="submitLoading">保存</el-button>
        </el-form-item>
        <el-form-item v-if="formTypeInfo.formType == 'search'">
            <el-button type="primary" @click="$emit('search')" v-if="formTypeInfo.searchBtn">搜索</el-button>
            <el-button plain @click="$emit('reset')" v-if="formTypeInfo.resetBtn">重置</el-button>
            <el-button plain @click="$emit('exportDownload')" v-if="formTypeInfo.exportBtn">导出</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    name: 'form-view',
    props: {
        inline: {
            type: Boolean,
            default: true,
        },
        labelWidth: {
            type: String,
            default: '80px',
        },
        form: {
            type: Object,
            default: () => { },
        },
        rules: {
            type: Object,
            default: () => { },
        },
        formTypeInfo: {
            type: Object,
            default: () => ({
                formType: 'search',
                searchBtn: true,
                resetBtn: true,
                exportBtn: false,
            }),
        },
    },
    data() {
        return {
            submitLoading: false,
        }
    },
    methods: {
        // 提交
        submit() {
            this.$refs['form-components'].validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true
                    try {
                        console.log('submit')
                        this.$emit('submit')
                    } catch (error) {
                        console.log('error')
                    } finally {
                        this.submitLoading = false
                        this.cancel()
                    }
                } else {
                    return false
                }
            })
        },
        // 取消
        cancel() {
            this.$refs['form-components'].resetFields()
            this.$emit('update:form', {})
            this.$emit('cancel')
        },
    }
}
</script>

<style scoped lang="scss">
.reason-btn {
    text-align: right;
}
</style>